package com.da.javatest.webflux.service.impl;

import java.util.HashMap;
import java.util.Map;

import com.da.javatest.webflux.entity.User;
import com.da.javatest.webflux.service.UserService;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * @author JokerDa.
 * @date 2021/1/6 15:11
 * Description:
 */
@Service
public class UserServiceImpl implements UserService {

    // 作为数据存储
    private final Map<Integer, User> users = new HashMap<>();

    public UserServiceImpl() {
        users.put(1, new User(1, "Joker", 20));
        users.put(2, new User(2, "Da", 22));
        users.put(3, new User(3, "张三", 23));
    }

    @Override
    public Mono<User> getUserById(int id) {
        return Mono.justOrEmpty(this.users.get(id));
    }

    @Override
    public Flux<User> getAllUser() {
        return Flux.fromIterable(users.values());
    }

    @Override
    public Mono<Void> saveUser(Mono<User> userMono) {
        return userMono.doOnNext(user -> users.put(user.getId(), user)).then(Mono.empty());
    }

    @Override
    public Mono<Void> deleteUser(int id) {
        return Mono.justOrEmpty(this.users.remove(id)).then(Mono.empty());
    }
}
